//
// Copyright 2011 ReedRex Corp
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// BlobContext.m
// Cloud BookShelf
//
// Created by Shunichi Takagi on 11/02/25.
//


#import "BlobContext.h"


@implementation BlobContext

@synthesize serviceURL;
@synthesize delegate;

- (id) initWithUri:(NSString *)aUri {
	self.serviceURL = aUri;
	return self;
}

- (NSData *) fetch:(NSString *)aBlob withContainer:(NSString *)aContainer {
	NSString *url = [NSString stringWithFormat:@"%@/%@/%@", self.serviceURL, aContainer, aBlob];
	NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
	
	[req setHTTPMethod:@"GET"];
	
	if( delegate ) {
		[delegate onSendRequest:req];
	}
	
	NSURLResponse* response;
	NSError* error = nil;
	NSData* result = [NSURLConnection sendSynchronousRequest:req
										   returningResponse:&response
													   error:&error];
	NSLog(@"%@", [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding]);
	if(error) NSLog(@"error = %@", error);
	
	[req release];
	
	return result;
}

- (void) store:(NSData *)data to:(NSString *)aBlob withContainer:(NSString *)aContainer {
	NSString *url = [NSString stringWithFormat:@"%@/%@/%@", self.serviceURL, aContainer, aBlob];
	NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
	
	[req setHTTPMethod:@"PUT"];
	[req addValue:@"BlockBlob" forHTTPHeaderField:@"x-ms-blob-type"];
	[req addValue:[NSString stringWithFormat:@"%d", [data bytes]] forHTTPHeaderField:@"Content-Length"];
	[req setHTTPBody:data];
	
	if( delegate ) {
		[delegate onSendRequest:req];
	}
	
	NSURLResponse* response;
	NSError* error = nil;
	NSData* result = [NSURLConnection sendSynchronousRequest:req
										   returningResponse:&response
													   error:&error];
	NSLog(@"%@", [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding]);
	if(error) NSLog(@"error = %@", error);
	
	[req release];
}

@end
